<template>
  <a-card>
    <a-form layout="horizontal" :form="searchForm" @submit="handleSearch" autocomplete="off">
      <a-row type="flex" justify="start" :gutter="30">
        <a-col :md="5" :sm="24">
          <a-form-item>
            <a-select :options="currencyCodes" v-decorator="['code']" :placeholder="$t('currency')">
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="14" :sm="24">
          <a-form-item>
            <a-space>
              <a-button htmlType="submit" type="primary" icon="search">{{$t('search')}}</a-button>
              <a-button type="primary" icon="plus" @click="showForm(null)">{{$t('add')}}{{$t('exrate')}}</a-button>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <a-table size="middle" :columns="columns" :data-source="data" :pagination="{ showSizeChanger: true, showQuickJumper: true, size:'middle', showTotal:(total, range) => `${range[0]}-${range[1]} / ${total}`, current: pageIndex, pageSize: pageSize, total: total, pageSizeOptions:['10','20','30','50','100','1000','2000'], }" :row-key="record => record.codeFrom + record.codeTo" :loading="loading" @change="handleTableChange">
      <div slot="exrate" slot-scope="text, record">
        <a-space>
          1 {{getCurrencyText(record.codeFrom)}} => {{record.rate}} {{getCurrencyText(record.codeTo)}}
        </a-space>
      </div>
      <div slot="action" slot-scope="text, record">
        <a-space>
          <a-button @click="showForm(record)">
            <a-icon type="edit"/>{{$t("edit")}}
          </a-button>
          <a-popconfirm :title='$t("are_you_sure")' ok-text="Yes" okType="danger" cancel-text="No" @confirm="deleteRate(record)">
            <a-icon slot="icon" type="question-circle-o" style="color: red" />
            <a-button><a-icon type="delete"/>{{$t("delete")}}</a-button>
          </a-popconfirm>
        </a-space>
      </div>
      <template v-for="(item, index) in columns" :slot="item.slotName">
        <span :key="index">{{ $t(item.slotName) }}</span>
      </template>
    </a-table>

    <a-modal v-model="editVisible" :maskClosable="false" :title="editTitle" :confirm-loading="confirmLoading" :okText="$t('submit')" @ok="saveForm()" @cancel="closeForm()">
      <a-form-model ref="updateForm" layout="inline" :model="updateForm" autocomplete="off" :rules="updateFormRules">
        <a-form-model-item  prop="codeFrom" :placeholder="$t('currency')">
          <a-select :options="codeFroms" v-model="updateForm.codeFrom" style="width: 150px" :placeholder="$t('currency')" :disabled="editReadonly">
          </a-select>
        </a-form-model-item>
        <a-form-model-item>=></a-form-model-item>
        <a-form-model-item prop="rate" :placeholder="$t('exrate')">
          <a-input-number v-model="updateForm.rate" :min="0">
          </a-input-number>
        </a-form-model-item>
        <a-form-model-item prop="codeTo" :readonly="editReadonly">
          <a-select :options="codeTos" v-model="updateForm.codeTo" style="width: 120px" :placeholder="$t('currency')" :disabled="editReadonly">
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-card>
</template>

<script>
import {getExrateList,updateExrate,deleteExrate} from '@/services/exchangerate'
export default {
  name: "ExchangeRate",
  i18n: require('../i18n'),
  data () {
    return {
      currencyCodes:[
        {value:"", label:"All"},
        {value:"CNY", label:"CNY 人民币"},
        {value:"USD", label:"USD 美元"},
        {value:"NZD", label:"NZD 新西兰元"},
        {value:"GBP", label:"GBP 英镑"},
        {value:"HKD", label:"HKD 港元"},
        {value:"JPY", label:"JPY 日元"},
        {value:"KRW", label:"KRW 韩元"},
        {value:"THB", label:"THB 泰国铢"},
      ],
      codeFroms:[
        {value:"CNY", label:"1 CNY 人民币"},
        {value:"USD", label:"1 USD 美元"},
        {value:"NZD", label:"1 NZD 新西兰元"},
        {value:"GBP", label:"1 GBP 英镑"},
        {value:"HKD", label:"1 HKD 港元"},
        {value:"JPY", label:"1 JPY 日元"},
        {value:"KRW", label:"1 KRW 韩元"},
        {value:"THB", label:"1 THB 泰国铢"},
      ],
      codeTos:[
        {value:"CNY", label:"CNY 人民币"},
        {value:"USD", label:"USD 美元"},
        {value:"NZD", label:"NZD 新西兰元"},
        {value:"GBP", label:"GBP 英镑"},
        {value:"HKD", label:"HKD 港元"},
        {value:"JPY", label:"JPY 日元"},
        {value:"KRW", label:"KRW 韩元"},
        {value:"THB", label:"THB 泰国铢"},
      ],
      searchParams: {},
      searchForm: this.$form.createForm(this, { name: 'search' }),
      pageIndex: 1,
      pageSize: 10,
      total:0,
      loading: false,
      data : [],
      columns:[
        {
          dataIndex: 'codeFrom',
          align:'left',
          slotName: "exrate",
          slots: { title: 'exrate' },
          scopedSlots: { customRender: 'exrate' },
        },{
          dataIndex: 'updatedByName',
          align:'center',
          slotName: "updatedByName",
          slots: { title: 'updatedByName' },
        },{
          dataIndex: 'updatedTime',
          align:'center',
          slotName: "updatedTime",
          slots: { title: 'updatedTime' },
        },{
          align:'center',
          scopedSlots: { customRender: 'action' },
          slotName: "operation",
          slots: { title: 'operation' },
        }
      ],
      updateForm: {
        codeFrom: "",
        codeTo: "",
        rate: 0,
        updatedBy: 0,
        updatedByName: "",
        updatedTime: ""
      },
      editVisible: false,
      editReadonly: false,
      editTitle:'',
      confirmLoading:false,
      updateFormRules: {
        codeTo: [{ required: true, message: ' ', trigger: 'blur' }],
        codeFrom: [{ required: true, message: ' ', trigger: 'blur' }],
      },
    }
  },
  methods: {
    handleSearch(e){
      e.preventDefault();
      this.searchForm.validateFields((error, values) => {
        this.searchParams = values;
      });
      this.pageIndex = 1
      this.fetchData()
    },
    fetchData(){
      this.loading = true
      getExrateList(this.pageIndex, this.pageSize, this.searchParams).then(res => {
        const {rows, total} = res.data.data
        this.data = rows
        this.total = total
        this.loading = false
      }).catch(error => {
        console.log(error)
        this.loading = false
      })
    },
    handleTableChange(pagination) {
      if(this.pageIndex === pagination.current && this.pageSize === pagination.pageSize)
        return

      this.pageIndex = pagination.current;
      this.pageSize = pagination.pageSize;
      this.fetchData()
    },
    showForm(exrate){
      if(exrate === null) {
        this.editTitle = this.$t('add') + this.$t('exrate')
        this.editReadonly = false
      }else{
        this.editTitle = this.$t('edit') + this.$t('exrate')
        this.updateForm = JSON.parse(JSON.stringify(exrate))
        this.editReadonly = true
      }
      this.editVisible = true;
    },
    saveForm(){
      this.$refs.updateForm.validate(valid => {
        if (valid) {
          console.log(this.updateForm)
          this.confirmLoading = true
          updateExrate(this.updateForm).then(res => {
            if(res.data.success) {
              this.$message.success({content: this.$t('submitSuccess')})
              this.closeForm()
              this.fetchData()
            }else{
              this.$message.error({content: this.$t(res.data.message)})
            }
          }).catch(error => {
            console.log(error)
          })
        } else {
          return false;
        }
      });
    },
    closeForm(){
      this.confirmLoading = false
      this.editVisible = false
      this.updateForm = {}
      this.$refs.updateForm.clearValidate()
    },
    deleteRate(exrate){
      deleteExrate(exrate.codeFrom, exrate.codeTo).then(res => {
        if(res.data.success) {
          this.$message.success({content: this.$t('deleteSuccess')})
          this.fetchData()
        }else{
          this.$message.error({content: this.$t(res.data.message)})
        }
      }).catch(error => {
        console.log(error)
      })
    },
    getCurrencyText(code){
      let currs = this.currencyCodes.filter(item => item.value === code)
      if(currs.length > 0)
        return currs[0].label;
      else
        return code;
    },
  },
  created() {
    this.fetchData()
  }
}
</script>